<!--
  -    Copyright (c) 2018-2025, hycloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: hycloud
  -->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @size-change="sizeChange"
                       @current-change="currentChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="rowDel">
                       <template slot="menuLeft">
                            <el-button
                            icon="el-icon-circle-plus"
                            size="small"
                            type="primary"
                            @click="choseMember('asset')">新增</el-button>
                        </template>
                        <template slot-scope="{ row }" slot="menu">
                            <el-button
                            v-if="row.status == '0'"
                            icon="el-icon-position"
                            type="text"
                            @click="toReceive(row)"
                            >完成养护</el-button
                            >
                            <el-button
                            v-if="row.status == '0'"
                            icon="el-icon-delete"
                            type="text"
                            @click="rowDel(row)"
                            >删除</el-button
                            >
                            <el-button
                            v-if="row.status == '1'"
                            icon="el-icon-position"
                            type="text"
                            @click="deviceshow(row)"
                            >查看记录</el-button
                            >
                        </template>
            </avue-crud>
        </basic-container>
        <el-dialog top="5vh" title="完成养护" v-if="modal3" :visible.sync="modal3" append-to-body>
        <avue-form
          ref="wcnjform"
          :option="wcnjoption"
          v-model="wcnjform"
          @submit="toaudit"
        >
          <template slot-scope="scope" slot="menuForm">
            <el-button icon="el-icon-close" @click="modal3 = false"
              >取消</el-button
            >
          </template>
          <template slot-scope="scope" slot="recordItemList">
            <div class="prdiv">
                <div>养护费用:</div>
                <avue-crud
                  ref="conscurd"
                  :option="itemOption"
                  :data="itemList || []"
                >
                  <template slot="menuLeft">
                    <el-button type="primary" size="small" @click="addConsumable()" style="margin-bottom: 15px;">添加</el-button>
                  </template>
                  <template
                    slot="menu"
                    slot-scope="{row}"
                  >
                    <el-button type="text" icon="el-icon-delete" @click="todelCbl(row)">删除</el-button>
                  </template>
                  <template slot="amount" slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.amount"
                      controls-position="right"
                      size="small"
                      :min="1"
                      @change="() => {comupdate(scope.row)}"
                      @blur="() => {comupdate(scope.row)}"
                    />
                  </template>
                </avue-crud>
                <div class="divs">
                  <table class style="width:100%;">
                    <tbody class>
                      <tr>
                        <td colspan="1" rowspan="1" class style="width:15.7%">
                          <div class="cell"></div>
                        </td>
                        <td colspan="1" rowspan="1" class style="width:10.9%">
                          <div class="cell"></div>
                        </td>
                        <td colspan="1" rowspan="1" class style="width:10.9%">
                          <div class="cell">合计:{{Number.isInteger(ctotal)?ctotal:ctotal.toFixed(2)}}</div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
          </template>
        </avue-form>
      </el-dialog>

      <el-dialog title="查看" v-if="modal4" :visible.sync="modal4" width="60%" append-to-body>
        <div v-loading="loading">
          <div class="form">
            <el-form ref="form" label-width="100px" label-position="left">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="计划:">
                    <span>{{
                      recordDetail ? recordDetail.planName : ""
                    }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计划日期:">
                    <span>{{ recordDetail ? recordDetail.planDate : "" }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="养护时间:">
                    <span>{{
                      recordDetail ? recordDetail.createTime : ""
                    }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="养护单位:">
                    <span>{{
                      recordDetail ? getUnitName(recordDetail.unitId) : ""
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="养护人:">
                    <span>{{
                      recordDetail ? recordDetail.handleRealname : ""
                    }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="设备状态:">
                    <span>{{
                      getZtName(recordDetail ? recordDetail.status : "")
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注:">
                    <span>{{ recordDetail ? recordDetail.content : "" }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row>
                <el-col :span="24">
                  <el-form-item label="文件列表:">
                    <div
                      v-if="
                        recordDetail &&
                        JSON.parse(recordDetail.imageMultiple) instanceof Array
                      "
                    >
                      <el-link
                        v-for="(item, index) in JSON.parse(
                          recordDetail.imageMultiple
                        )"
                        :key="index"
                        :underline="false"
                        type="primary"
                        class="fileList"
                        @click="filedownload(item.url, item.originName)"
                        >{{ item.originName }}</el-link
                      >
                    </div>
                  </el-form-item>
                </el-col>
              </el-row> -->

              <el-row>
                <el-col :span="24">
                  <avue-crud
                    :option="fyoperationOption"
                    :data="fyoperationData"
                  >
                    <template slot-scope="scope" slot="menuLeft"> 养护费用： </template>
                  </avue-crud>
                  <div class="divs">
                  <table class style="width:100%;">
                    <tbody class>
                      <tr>
                        <td colspan="1" rowspan="1" class style="width:15.7%">
                          <div class="cell"></div>
                        </td>
                        <td colspan="1" rowspan="1" class style="width:10.9%">
                          <div class="cell"></div>
                        </td>
                        <td colspan="1" rowspan="1" class style="width:10.9%">
                          <div class="cell">合计:{{fytotal}}</div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </el-dialog>
       <el-dialog
        top="5vh"
        width="85%"
        title="添加"
        append-to-body
        :visible.sync="consumabledrawer"
        v-if="consumabledrawer"
      >
        <div>
              <avue-crud
                ref="consumable_multipleTable"
                :page.sync="consumable_page"
                :data="consumable_tableData"
                v-model="consumable_userform"
                :table-loading="consumable_tableLoading"
                :option="consumable_tableOption"
                @search-change="consumable_searchChange"
                @on-load="consumable_getList"
                @size-change="consumable_sizeChange"
                @current-change="consumable_currentChange"
                @selection-change="selectionChange"
              >
              </avue-crud>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="consumabledrawer = false">取 消</el-button>
          <el-button type="primary" @click="toaddCbl">确 定</el-button>
        </div>
      </el-dialog>
        <choose-member v-if="showChose" :labelkey="labelkey" :url1="url1" :url2="url2" :title="title" :columns1="columns1" :columns="columns" :limitLabel="limitLabel" :flKey="flKey" :type="type" :validClose="validClose"></choose-member>
    </div>
</template>

<script>
    import {fetchList, complete, addObj, putObj, delObj} from '@/api/maintenance/maintenanceplanasset'
    import {fetchList as fetchList1} from '@/api/maintenance/maintenanceitem'
    import {fetchList as fetchList2} from '@/api/maintenance/maintenanceunit'
    import {getObj} from '@/api/maintenance/maintenancerecord'
    import eventBus from '@/util/eventBus'
    import { remote } from "@/api/admin/dict";
    import chooseMember from '@/components/chooseMember'
    import {tableOption, wcnjoption, itemOption, fyoperationOption, consumable_tableOption} from '@/const/crud/maintenance/maintenanceplanasset'
    import {mapGetters} from 'vuex'

    export default {
        components: { chooseMember },
        props: ['planId'],
        name: 'maintenanceplanasset',
        data() {
            return {
                showChose: false,
                edom: '',
                url1: '',
                validClose: true,
                url2: '',
                type: 'checkbox',
                limitLabel:'',
                columns:[],
                columns1:[],
                title: '',
                flKey: '',
                labelkey: '',
                searchForm: {},
                tableData: [],
                modal3: false,
                wcnjform: {},
                wcnjoption: wcnjoption,
                deviceId: "",
                modal4: false,
                loading: false,
                recordDetail: {},
                fyoperationOption:fyoperationOption,
                fyoperationData:[],
                fytotal:0,
                planAssetId: '',
                assetId: '',
                assetName: '',
                itemOption:itemOption,
                consumabledrawer: false,
                consumable_searchForm: {},
                consAddList: [],
                consumable_page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                optionsZt: [],
                itemList:[],
                consumable_tableData: [],
                consumable_userform: {},
                consumable_tableLoading: false,
                consumable_tableOption: consumable_tableOption,
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                unitList: [],
                ctotal:0,
                deviceStatus:'',
                deviceStatusList:[],
                radio:'',
                tableLoading: false,
                tableOption: tableOption
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: false,
                    delBtn: false,
                    editBtn: false
                };
            }
        },
        created() {
            this.eventBusHandle()
            this.init()
        },
        methods: {
            init() {
                fetchList2({size: -1}).then(response => {
                    this.unitList = response.data.data.records
                })
                remote('maintenance_record_status').then(response => {
                  this.optionsZt = response.data.data
                })
            },
            getZtName(id) {
                let list = this.optionsZt.filter(item => {
                    return item.value === id
                })
                return list.length ? list[0].label: ''
            },
            getUnitName(id) {
                let list = this.unitList.filter(item => {
                    return item.unitId === id
                })[0]
                return list.name
            },
            // /子计划 设备/
            toReceive(row) {
                this.itemList=[];
                this.consAddList = []
                Object.keys(this.wcnjform).map(item => {
                    if (typeof this.wcnjform[item] == 'string') {
                    this.wcnjform[item] = ""
                    } else {
                    this.wcnjform[item] = []
                    }
                });
                this.wcnjform.status = '1'
                this.ctotal=0;
                this.planAssetId=row.planAssetId
                this.assetId=row.assetId
                this.assetName=row.name
                this.modal3 = true;
            },
            comupdate() {
                this.ctotal = 0
                let hcrepairItemList = this.itemList;
                    hcrepairItemList.forEach((ele) => {
                    if (!ele.price) {
                        ele.price = 0
                    }
                    if (ele.amount) {
                        this.ctotal+=(ele.price*ele.amount)
                    } else {
                        this.ctotal+=0
                    }
                });
            },
            addConsumable(){
                this.consumable_searchForm = {};
                this.consumable_page.currentPage = 1;
                this.consAddList = [];
                this.consumabledrawer = true
            },
            toaudit(form, done) {
                if (this.consAddList.length > 0) {
                    let flag = true
                    this.consAddList.map(item => {
                        if (!item.amount && item.amount !== 0 && flag) {
                            this.$message.warning("请输入项目数量");
                            done()
                            flag = false
                        }
                    })
                    if (flag) {
                        this.wcnjform.recordItemList = this.consAddList
                        this.wcnjform.totalPrice = this.ctotal
                        this.wcnjform.planAssetId = this.planAssetId
                        this.wcnjform.planId = this.planId
                        this.wcnjform.assetId = this.assetId
                        this.wcnjform.assetName = this.assetName
                        complete(this.wcnjform).then(response => {
                            this.$message.success("提交成功")
                            this.modal3 = false
                            this.getList(this.page)
                        }).catch(() => {
                            done();
                        });
                    }
                } else {
                    this.$message.warning("请选择养护项目");
                    done()
                }
            },
            toaddCbl() {
                if (this.consAddList.length > 0) {
                    this.itemList = [...this.itemList, ...this.consAddList];
                    const ids = {};
                    const newArr = this.itemList.filter((val, index) => {
                    if (val.itemId in ids) {
                        this.itemList[ids[val.itemId]].amount += val.amount
                        return false
                    } else {
                        ids[val.itemId] = index
                        return true
                    }
                    })
                    this.itemList = newArr;
                    this.consAddList = Object.assign([], newArr);
                    this.ctotal = 0;
                    let hcrepairItemList = this.itemList;
                    hcrepairItemList.forEach((ele) => {
                    if (!ele.price) {
                        ele.price = 0
                    }
                    this.ctotal+=(ele.price*ele.amount) ;
                    });
                    this.consumabledrawer = false;
                } else {
                    this.$message.warning("请选择项目");
                }
            },
            todelCbl(row){
                this.itemList.splice(this.itemList.findIndex((v, i) => i === row.$index), 1);
                this.consAddList.splice(this.consAddList.findIndex((v, i) => i === row.$index), 1);
                this.ctotal = 0;
                    let hcrepairItemList = this.itemList;
                    hcrepairItemList.forEach((ele) => {
                    if (!ele.price) {
                        ele.price = 0
                    }
                    this.ctotal+=(ele.price*ele.amount) ;
                });
            },
            consumable_sizeChange(pageSize) {
                // this.$refs.consumable_multipleTable.toggleSelection();
                this.consumable_page.pageSize = pageSize;
            },
            consumable_currentChange(current) {
                // this.$refs.consumable_multipleTable.toggleSelection();
                this.consumable_page.currentPage = current;
            },
            consumable_searchChange(form, done) {
                this.$refs.consumable_multipleTable.toggleSelection();
                this.consumable_page.currentPage = 1;
                this.consumable_searchForm = form;
                this.consumable_getList(this.consumable_page, form);
                done()
            },
            consumable_getList(page, params) {
                this.consumable_tableLoading = true
                fetchList1(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    status: '1'
                }, params, this.consumable_searchForm)).then(response => {
                    response.data.data.records.forEach((ele) => {
                    ele.amount = 1;
                    })
                    this.consumable_tableData = response.data.data.records
                    this.consumable_page.total = response.data.data.total
                    this.consumable_tableLoading = false
                }).catch(() => {
                    this.consumable_tableLoading = false
                })
            },
            selectionChange(list) {
              console.log(list)
                this.consAddList = list;
            },
             eventBusHandle () {
                let _this = this
                eventBus.$off('getMember')
                eventBus.$on('getMember', function (data) {
                    if(data.assetList_choose_member && data.assetList_choose_member.length) {
                        let params = {
                            assetIds: data.assetList,
                            planId: _this.planId
                        }
                        addObj(params).then(data => {
                            _this.showChose = false
                            _this.$message.success('添加成功')
                            _this.getList(_this.page)
                            _this.flag = false
                        }).catch(() =>{
                        })
                    }
                })
            },
            choseMember (id) {
                this.labelkey = 'assetList_choose_member'
                this.showChose = true
                this.url1 = '/act/assetcategory/tree?status=1'
                this.url2 = '/act/asset/page'
                this.title = '资产类别'
                this.limitLabel = '添加资产'
                this.columns = [
                    {
                        title: '资产名',
                        dataIndex: 'name',
                        key: 'name',
                        width: 150
                    },
                    {
                        title: '规格',
                        key: 'spec',
                        width: 80,
                        dataIndex: 'no',
                    },
                    {
                        title: '单位',
                        key: 'unit',
                        width: 80,
                        dataIndex: 'unit',
                    },
                    {
                        title: '编号',
                        key: 'no',
                        width: 100,
                        dataIndex: 'no',
                    },
                    {
                        title: 'sn',
                        key: 'sn',
                        width: 80,
                        dataIndex: 'sn',
                    },
                    {
                        title: '品牌',
                        key: 'brand',
                        width: 80,
                        dataIndex: 'brand',
                    }
                ]
                this.flKey = 'categoryId'
                this.columns1 = [
                    {
                        title: '资产名',
                        dataIndex: 'name',
                        key: 'name' 
                    },
                    {
                        title: '操作',
                        key: 'action',
                        scopedSlots: { customRender: 'action' },
                    },
                ]
            },
            getList(page, params) {
                this.tableLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    planId: this.planId
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            rowDel: function (row, index) {
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.planAssetId)
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            deviceshow(row) {
                this.recordDetail = {};
                this.loading = true;
                getObj(row.recordId).then((res) => {
                    this.recordDetail = res.data.data;
                    this.modal4 = true
                    this.loading = false
                    this.fyoperationData = res.data.data.recordItemList
                    this.fytotal = res.data.data.totalPrice
                }).catch(() => {
                    this.loading = false;
                });
            },
            handleUpdate: function (row, index, done,loading) {
                putObj(row).then(data => {
                    this.$message.success('修改成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleSave: function (row, done,loading) {
                addObj(row).then(data => {
                    this.$message.success('添加成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>